
//
//  ResultInputViewController.m
//  AndCampus
//
//  Created by 史宵宵 on 2017/12/6.
//  Copyright © 2017年 史宵宵. All rights reserved.
//

#import "ResultInputViewController.h"
#import "loginTextField.h"
#import "ResultInfo.h"

@interface ResultInputViewController ()<UITextFieldDelegate>
@property(nonatomic,strong)NSMutableArray *dataArray;
@property (nonatomic,strong) NSMutableArray *textValeArray; //数组的值 数组
@property (nonatomic,assign) BOOL isEdit;
@end

@implementation ResultInputViewController
- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray=[NSMutableArray array];
    }
    return _dataArray;
}
- (NSMutableArray *)textValeArray{
    if (!_textValeArray) {
        _textValeArray = [NSMutableArray array];
    }
    return _textValeArray;
}
- (UIStatusBarStyle)preferredStatusBarStyle{
    
    return UIStatusBarStyleLightContent;
    
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    //    [Global setStatusBarBackgroundColor:[UIColor clearColor]];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"录入成绩";
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    if (![self.resultInputType isEqualToString:@"newInput"]) {
        self.navigationItem.rightBarButtonItem = [UIBarButtonItem leftBarButtonItemWithTitle:@"修改" target:self selector:@selector(editResultInput)];
        self.isEdit = NO;
    }else{
        self.isEdit = YES;
    }
    [self creatFootView];
    [self creatData];
}
- (void)creatFootView{
    UIView *footView = [[UIView alloc]init];
    footView.frame = CGRectMake(0, 0, kScreenW, 100);
    footView.backgroundColor = [UIColor whiteColor];
    self.tableView.tableFooterView = footView;
    
    
    CompleteButton *completeButton = [[CompleteButton alloc]initWithFrame:CGRectMake(10, 20, kScreenW - 20, 40) bgColor:KBACKNAVIGATIONCOLOR tColor:[UIColor whiteColor] text:@"确认"];
    completeButton.userInteractionEnabled = self.isEdit;
    [completeButton addTarget:self action:@selector(sureData) forControlEvents:UIControlEventTouchUpInside];
    [footView addSubview:completeButton];
}
#pragma mark - 修改成绩
- (void)editResultInput{
    self.isEdit = YES;
    [self creatFootView];
    [self.tableView reloadData];
}
#pragma mark - 编辑数据时请求全部数据
- (void)creatData{
    [self.tableView endEditing:YES];
    
    YJNetWorkManger *yjNetWorkManger =  [YJNetWorkManger shareManager];
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    NSString *url ;
    if ([self.resultInputType isEqualToString:@"newInput"]) { //请求科目列表
        url = [JSPathUtil urlAppHomePageGetUserScoreGade];
    }else{
        url = [JSPathUtil urlAppHomePageGetUserScoreList];
        [dic setValue:self.yearStr forKey:@"execute_year"];   //年度
        [dic setValue:self.monthStr forKey:@"execute_month"];   //月份
    }
    [dic setValue:[Global getUserTokenInfo] forKey:@"token"]; //用户的token
    [yjNetWorkManger requestType:POST andURL:url andParmas:dic andComplition:^(id response, BOOL isuccess) {
        if (isuccess) {
            NSArray *allArray = [NSArray arrayWithArray:response];
            [ResultInfo mj_setupReplacedKeyFromPropertyName:^NSDictionary *{
                return @{@"resultId" : @"id"};
            }];
            [self.dataArray addObjectsFromArray:[ResultInfo mj_objectArrayWithKeyValuesArray:allArray]];
            for (int i = 0; i < self.dataArray.count; i ++) {
                [self.textValeArray addObject:@""];
            }
            [self.tableView reloadData];
        }
    }];
}

#pragma mark - 确认数据
- (void)sureData{
    [self.tableView endEditing:YES];
    
    YJNetWorkManger *yjNetWorkManger =  [YJNetWorkManger shareManager];
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    [dic setValue:[Global getUserTokenInfo] forKey:@"token"]; //用户的token
    [dic setValue:self.yearStr forKey:@"execute_year"];   //年度
    [dic setValue:self.monthStr forKey:@"execute_month"];   //月份
    
    NSMutableArray *scoreArray = [[NSMutableArray alloc]init];
    int allScore = 0;
    for (int i = 0; i < self.dataArray.count; i++) {
        ResultInfo *resultInfo = self.dataArray[i];
        allScore = allScore + [resultInfo.score intValue];
        NSMutableDictionary *muDic = [[NSMutableDictionary alloc]init];
        [muDic setValue:resultInfo.subject_id forKey:@"key"];
        [muDic setValue:resultInfo.score forKey:@"score"];
        [scoreArray addObject:muDic];
    }
    
    
    if ( !strIsEmpty(self.gadeIds)) {
        [dic setValue:self.gadeIds forKey:@"gade_ids"];   //成绩执行月度表ID
    }
    [dic setValue:[NSString stringWithFormat:@"%d",allScore] forKey:@"scoreSum"];   //总分
    NSData *dataFriends = [NSJSONSerialization dataWithJSONObject:scoreArray options:NSJSONWritingPrettyPrinted error:nil];
    NSString *jsonString = [[NSString alloc] initWithData:dataFriends encoding:NSUTF8StringEncoding];
    [dic setValue:jsonString forKey:@"parameter_score"];   //"{"key":"classId 科目值","score":"分数"}"
    
    [yjNetWorkManger requestType:POST andURL:[JSPathUtil urlAppHomePageSaveUserScore] andParmas:dic andComplition:^(id response, BOOL isuccess) {
        if (isuccess) {
            [Global showActivityWithView:self.view withText:@"修改成功"];
            if (self.resultInputSuccessBlock) {
                self.resultInputSuccessBlock();
            }
            [self.navigationController popViewControllerAnimated:YES];
        }
    }];
}
- (NSInteger )numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:nil];
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    
    ResultInfo *resultInfo = self.dataArray[indexPath.row];
    UILabel *label = [[UILabel alloc]init];
    label.frame = CGRectMake(0, 15, 100, 20);
    label.text = resultInfo.subject_name;
    label.textAlignment = NSTextAlignmentRight;
    [cell.contentView addSubview:label];
    
    loginTextField *loginTF = [[loginTextField alloc]initWithFrame:CGRectMake(105, 5, kScreenW - 160 , 40) placeholder:@"" imageStr:@""];
    loginTF.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
    loginTF.tag = 1000 + indexPath.row;
    loginTF.text = [NSString stringWithFormat:@"%.1f",[resultInfo.score floatValue]];
    loginTF.delegate = self;
    loginTF.userInteractionEnabled = self.isEdit;
    [cell.contentView  addSubview:loginTF];
    
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 45;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSCharacterSet *cs;
    cs = [[NSCharacterSet characterSetWithCharactersInString:kNumbersPeriod] invertedSet];
    NSString *filtered =
    [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
    BOOL basic = [string isEqualToString:filtered];
    if (!basic) 
    {
        [Global showActivityWithView:self.view withText:@"只能输入数字"];
        return NO;
    }
    if ([textField.text containsString:@"."]) {
        NSRange range = [textField.text rangeOfString:@"."];
        if ([textField.text stringByAppendingString:string].length - range.location >2) {
            [Global showActivityWithView:self.view withText:@"小数点后保留一位小数"];
            return NO;
        }
        if ([string isEqualToString:@"."]) {
            [Global showActivityWithView:self.view withText:@"成绩不能有俩个小数点"];
            return NO;
        }
    }
    
    if ([[textField.text stringByAppendingString:string] floatValue] >300) {
        [Global showActivityWithView:self.view withText:@"成绩不能大于300"];
        return NO;
    }
    return YES;
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField{
    ResultInfo *resultInfo = self.dataArray[textField.tag - 1000];
    resultInfo.score = textField.text;
    [self.dataArray replaceObjectAtIndex:textField.tag - 1000 withObject:resultInfo];
    
    [self.textValeArray replaceObjectAtIndex:textField.tag - 1000 withObject:textField.text];
    [textField resignFirstResponder];
    return YES;
}
-(void)textFieldDidEndEditing:(UITextField *)textField
{
    ResultInfo *resultInfo = self.dataArray[textField.tag - 1000];
    resultInfo.score = textField.text;
    [self.dataArray replaceObjectAtIndex:textField.tag - 1000 withObject:resultInfo];
    
    [self.textValeArray replaceObjectAtIndex:textField.tag - 1000 withObject:textField.text];
    [textField resignFirstResponder];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    return [textField resignFirstResponder];
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view = [[UIView alloc]init];
    view.frame = CGRectMake(0, 0, kScreenW, 10);
    view.backgroundColor = [UIColor whiteColor];
    
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10.01f;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
